package com.xunyun.kotlinwc.login.repository

import android.annotation.SuppressLint
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.xunyun.kotlinwc.login.api.LoginService
import com.xunyun.kotlinwc.login.model.UserBean
import com.xunyun.kotlinwc.network.RetrofitHolder
import com.xunyun.kotlinwc.network.exception.ApiException
import com.xunyun.kotlinwc.network.exception.ErrorConsumer
import com.xunyun.kotlinwc.network.lifecycle.RxLifeCycle
import com.xunyun.kotlinwc.network.response.ResponseTransformer
import io.reactivex.functions.Consumer

/**
 * @author gl
 * @date 2021/9/8
 * @desc
 */
class LoginRepository {

    companion object {
        private var instance: LoginRepository? = null
            get() {
                if (field == null) {
                    field = LoginRepository()
                }
                return field
            }

        @Synchronized
        fun get(): LoginRepository {
            return instance!!
        }
    }

    @SuppressLint("CheckResult")
    fun getUser(
        name: String, password: String, lifecycleOwner: LifecycleOwner,
        loginLiveData: MutableLiveData<UserBean>, infoMsg: MutableLiveData<String>,
        isLoading: MutableLiveData<Boolean>
    ) {
        isLoading.value = true;
        RetrofitHolder.singleton.getRetrofit()
            .create(LoginService::class.java)
            .login(name, password)
            .compose(ResponseTransformer())
            .compose(RxLifeCycle(lifecycleOwner))
            .subscribe(Consumer {
                isLoading.value = false;
                loginLiveData.value = it?.run {
                    this
                }
            }, object : ErrorConsumer() {
                override fun error(apiException: ApiException?) {
                    isLoading.value = false;
                    infoMsg.value = apiException?.let {
                        it.msg
                    }
                }
            })


    }



}


